var activeStr = '1'; // 时间类型 1 待开始
// Tab切换 新建好活动和已建活动
$('.mi-t span').each(function (index) {
    $(this).mouseover(function () {
        $('section').eq(index).toggleClass('active').siblings().removeClass('active');
        $(this).toggleClass('mit-s').siblings().removeClass('mit-s');
        console.log('获取到的最初的值是什么++=======' + index)
        if (index == 0) {
            // setUp(); // 如果是待开始；掉新建活动
            console.log(index, '+++++++++++++')
        } else if (index == 1) {
            obtainList(); // 进行中,调获取列表的方法
        }
        // $('#newActivity').html() // 局部刷新
    })

});

// Tab切换 开始，进行中，取消

indexActivity();
function indexActivity() {
    var btns = document.getElementById("btns").getElementsByTagName("button");
    for (var i = 0; i < btns.length; i++) {
        btns[i].index = i; //自定义属性，用于关联下面的大盒子
        btns[i].onclick = function () {

            for (var j = 0; j < btns.length; j++) {
                //把所有的button清空类名
                btns[j].className = "";
            }
            //点击的那个盒子添加指定类名
            this.className = "movable";

            console.log(this.index)

            if (this.index == 0) {
                activeStr = '1';
                // dialog('没了')
            } else if (this.index == 1) {
                activeStr = '2';
                console.log('点击进行中')

            } else if (this.index == 2) {
                activeStr = '3';
                console.log('点击已结束')

            }

            $('#listStrId').html(); // 局部刷新一下页面
            obtainList();
        }
    }
}


var newTime = timeAll(); // ?? $里面是否能访问的奥
// 拼接时间戳，后台规定
var timestamp = 'timeStamp:' + newTime + 'BM';
// 时间戳md5加密 签名
var signs = md5(timestamp);
// 加密后的数据变成大写
signs = signs.toUpperCase();

//  封装一个uuid的方法
function S4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}

function guid() {
    return (S4() + S4() + S4() + S4() + S4() + S4() + S4()) + S4(); // 一个s4 是4位
}

// 获取当前时间
function getNowFormatDate() {
    var date = new Date();
    var seperator1 = "-";
    var seperator2 = ":";
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
        + " " + date.getHours() + seperator2 + date.getMinutes()
        + seperator2 + date.getSeconds();
    return currentdate;
}

//  新建活动活动
function setUp() {

    var uuid = guid();
    var activityName = $('#activityName').val();
    var activityContent = $('#aContent').val();
    console.log(activityContent);
    var beginStr = $('#sdate').val();
    var endStr = $('#edate').val();
    beginStr = beginStr.replace('-', ""); // 转移字符
    beginStr = beginStr.replace('-', "");
    endStr = endStr.replace('-', "");
    endStr = endStr.replace('-', "");
    var timestamp = 'timeStamp:' + newTime + 'BM' + 'startDate:' + beginStr + 'BM' + 'endDate:' + endStr + 'BM' + 'activityType:' + 2 + 'BM' + 'activityName:' + activityName + 'BM' + 'content:' + activityContent + 'BM' + 'id:' + uuid + 'BM';
    var signs = md5(timestamp);
    signs = signs.toUpperCase();

    $.ajax({
        type: 'get',
        url: webUrl + 'createActivity/execute',
        data: {
            "sign": signs,
            "timeStamp": newTime,
            "startDate": beginStr,
            "endDate": endStr,
            "activityType": 2,
            "activityName": activityName,
            "content": activityContent,
            "id": uuid,
        },
        dataType: 'JSON',
        async: false,
        success: function (data) {
            console.log(data, "创建活动");
            if (data.status == '200') {
                dialog('恭喜您活动创建成功'); // 清空
                document.getElementById("activityName").value = '';
                document.getElementById("sdate").value = '';
                document.getElementById("edate").value = '';
                document.getElementById("aContent").value = '';
            } else if (data.status == '300') {
                document.location.href = '../html/login.html';
            } else if(data.status =='500'){
                dialog(data.msg)
            }
        },
        error:function (data) {
            dialog(data.msg)
        }
    })
}

$('#showReceipt').on('click', function () {
    $receipt.fadeIn(200);
});

//  获取活动列表
function obtainList() {
    var timestamp = 'timeStamp:' + newTime + 'BM' + 'pageNum:' + 1 + 'BM' + 'pageSize:' + 10 + 'BM' + 'timeType:' + activeStr + 'BM';
    var signs = md5(timestamp);
    signs = signs.toUpperCase()
    $.ajax({
        type: 'get',
        url: webUrl + 'activityCenter/getActivityInfoList',
        data: {
            "sign": signs,
            "timeStamp": newTime,
            "pageNum": 1,
            "pageSize": 10,
            "timeType": activeStr,
        },
        dataType: 'JSON',
        async: false,
        success: function (data) {
            console.log(data);
            $('#activeContent').html(data);// 刷新页面 获取列表处理后刷新页面  ** ？
            // 遍历
            if (data.status == '200') {
              // data.data.length==0?dialog('没有活动列表': dialog()
                if(data.data.length==0){
                    dialog('目前没有活动列表')
                }
                // 存放所有的数据
                var item = data.data;
                console.log(item);
                for (var i = 0; i < item.length; i++) {
                    // 计算时时间差。时间戳之间才可以计算，开始时间戳——当前的时间错
                    var begintime_ms = getNowFormatDate(); // 获取当前时间
                    begintime_ms = Date.parse(new Date(begintime_ms.replace(/-/g, "/"))); //begintime 为当前时间戳
                    var sttime = item[i].startDate; // 开始时间
                    sttime_ms = Date.parse(new Date(sttime.replace(/-/g, "/")));   // endtime 为开始时间时间时间戳
                    var endTime = item[i].endDate;
                    endTime_ms = Date.parse(new Date(endTime.replace(/-/g, '/')));

                    var date1 = new Date();  //开始时间 new 一个现在的时间
                    console.log(date1, 'BBBBBBBBBBBBBBBBBBBBB')

                    var date3 = sttime_ms - date1.getTime(); //时间差的毫秒数
                    date3 = Number(date3);
                    var date4 = endTime_ms - date1.getTime();
                    date4 = Number(date4);
                    console.log(date4)

//计算出相差天数
                    var days = Math.floor(date3 / (24 * 3600 * 1000));
                    var days_over = Math.floor(date4 / (24 * 3600 * 1000))
//计算出小时数

                    var leave1 = date3 % (24 * 3600 * 1000);   //计算天数后剩余的毫秒数\
                    var leave_one = date4 % (24 * 3600 * 1000);
                    var hours = Math.floor(leave1 / (3600 * 1000));//计算相差分钟数
                    var hours_one = Math.floor(leave_one / (3600 * 1000))
                    var leave2 = leave1 % (3600 * 1000);        //计算小时数后剩余的毫秒数
                    var leave_two = leave_one % (3600 * 1000);
                    var minutes = Math.floor(leave2 / (60 * 1000));
                    var minutes_two = Math.floor(leave_two / (60 * 1000));
//计算相差秒数
                    var leave3 = leave2 % (60 * 1000);     //计算分钟数后剩余的毫秒数
                    var seconds = Math.round(leave3 / 1000);
                    // alert(" 相差 " + days + "天 " + hours + "小时 " + minutes + " 分钟" + seconds + " 秒");
// 还差多少时间开始
                    var delta_T = " 相差 " + days + "天 " + hours + "小时 " + minutes + " 分钟";
// 还差多少时间结束
                    var delta_over = " 相差 " + days_over + "天 " + hours_one + "小时 " + minutes_two + " 分钟";

                    var buttonStr;
                    var oneselfFound; // 商家自己创建的活动
                    var buttonStrTwo = new String();
                    indexID = item[i].id; // 保存获取的活动ID 作为参数直接传到所呀调的函数中去。

                    // 通过判断活动的状态得到不同的值
                    if (activeStr == '1') {

                        buttonStr = '<div class="abtn" onclick=abolishActivity(\"' + indexID + '\")>' + "取消活动" + "</div>" +
                            '<div class="adivision"></div>';
                        dateStr = "<p>" + delta_T + "</p>";
                    } else if (activeStr == "2") {
                        buttonStr = '<div class="abtn" onclick=abolishActivity(\"' + indexID + '\")>' + "下架活动" + "</div>" +
                            '<div class="adivision"></div>';
                        dateStr = "<p>" + delta_over + "</p>"
                    } else if (activeStr == "3") {
                        // 商家
                        buttonStr = '<div class="abtn" onclick=deleteActivity(\"' + indexID + '\")>' + "删除活动" + "</div>" +
                            '<div class="adivision"></div>';


                        terraceStr = terraceStr + buttonStrTwo
                        dateStr = '';
                    }

                    if (item[i].activityType == 1) {
                        // activityType == 1 是平台发布的活动 2 为商家自建的活动
                        var terraceStr;
                        terraceStr = "<div class='terraceFounde'>" +
                            "<p>" + "活动内容：" + item[i].activityName + "</p>" +
                            "<p>" + "活动ID：" + item[i].id + "</p>";
                        terraceStr = terraceStr + dateStr +
                            "<hr>" +
                            "<p>" + "类型：" + item[i].activityType + "</p>" +
                            "<p>" + "内容：" + item[i].content + "</p>" +
                            "<p>" + "日期:" + item[i].startDate + "——" + item[i].endDate + "</p>" +
                            "<hr>" +
                            "</div>"
                        $('#activeContent').append(terraceStr);

                    } else if (item[i].activityType == 2) {
                        console.log(indexID, '噼噼啪啪铺铺铺铺铺铺铺铺铺铺铺铺铺铺铺铺铺铺铺')
                        oneselfFound = "<div class='oneselfFound'>" +
                            "<p>" + "活动名称: " + item[i].activityName + "</p>" +
                            "<p id='aindexID'>" + "活动ID: " + item[i].id + "</p>";
                        oneselfFound = oneselfFound + dateStr +
                            "<hr>" +
                            "<p>" + "类型：" + item[i].activityType + "</p>" +
                            "<p>" + "内容：" + item[i].content + "</p>" +
                            "<p>" + "日期:" + item[i].startDate + "——" + item[i].endDate + "</p>" +
                            "<hr>" +
                            "</div>";
                        oneselfFound = oneselfFound + buttonStr;
                        $('#activeContent').append(oneselfFound);
                    }
                }

            }
            else if (data.status == '300') {
                document.location.href = '../html/login.html';
            } else if (data.status == '500') {
                dialog(data.msg)
            }

        }
    })
}

// 取消
function abolishActivity(id) {
    var ID = id;
    var timestamp = 'timeStamp:' + newTime + 'BM' + 'activityId:' + ID + 'BM'; // 拼接
    var signs = md5(timestamp);// 加密
    signs = signs.toUpperCase();
    $.ajax({
        type: 'get',
        url: webUrl + 'activityCenter/deleteCancelActivity',
        data: {
            "sign": signs,
            "timeStamp": newTime,
            "activityId": ID,
        },
        dataType: 'JSON',
        async: false,
        success: function (data) {
            console.log(data, '----------- 取消活动');
            // 200，
            if (data.status == '200') {
                obtainList();
                // if(activeStr == '3'){
                //     $(".oneselfFound").removeData();
                //     $('.terraceFounde'); // 把所有的都移除了。
                // } else {
                //     $(".oneselfFound").removeData();
                //     obtainList()
                // }
                dialog('取消成功');
            } else if (data.startDate == '300') {
                document.location.href = '../html/login.html';
            } else if (data.status == '500') {
                dialog('活动不存在')
                // $('.terraceFounde').remove(); // 取消成功，页面上没有移除

            }
        }
    })
}

// 删除活动
function deleteActivity(id) {
    var timestamp = 'timeStamp:' + newTime + 'BM' + 'activityId:' + ID + 'BM'; // 拼接
    var signs = md5(timestamp);// 加密
    signs = signs.toUpperCase();
    $.ajax({
        type: 'get',
        url: webUrl + 'activityCenter/deleteActivity',
        data: {
            "sign": signs,
            "timeStamp": newTime,
            "activityId": id,
        },
        dataType: 'JSON',
        async: false,
        success: function (data) {
            console.log(data, '---------  删除活动活动')
            // 200，
            if (data.status == '200') {
                // $(".oneselfFound").removeData();
                obtainList();
                dialog('删除成功');
            } else if (data.startDate == '300') {
                document.location.href = '../html/login.html';
            } else if (data.status == '500') {
                // dialog('活动不存在')
                // $('#activeContent').html = ''


            }
        }
    })
}


// 参见活动 占时用不到
// function joinActivity() {
//     $.ajax({
//         type: 'get',
//         url: webUrl + 'activityCenter/addAttendActivity',
//         data: {
//             "sign": signs,
//             "timeStamp": timestamp,
//             "activityId": indexID,
//
//         },
//         dataType: 'JSON',
//         async: false,
//         success: function (data) {
//             console.log(data, '欢迎参加活动');
//             if(data.status=='200'){
//                 $('#activeContent').html();
//             } else if (data.startDate == '300') {
//                 document.location.href = '../html/login.html';
//             } else if (data.status == '500') {
//                 // dialog('活动已经参加，不能重复参加')
//             }
//         }
//     })
// }